package com.qf.controller.shangpin_controller;

import com.github.pagehelper.PageInfo;
import com.qf.bean.*;
import com.qf.dao.kucun_dao.GoodsDao;
import com.qf.dao.shangpin_dao.BrandDao;
import com.qf.dao.shangpin_dao.ChDao;
import com.qf.dao.shangpin_dao.TypeDao;
import com.qf.service.shangpin_service.ChService;
import com.qf.service.shangpin_service.CommService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 10/12/2019
 * Echo
 * sassspringboot
 * Alibaba
 */
@Controller
public class CommodityController {

    @Autowired
    private CommService commService;
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private TypeDao typeDao;


    @RequestMapping("/daochu")
    public void daochu(int[] ids,HttpServletResponse response) throws IOException {
//        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//        for (int id : ids) {
//            System.out.println(id);
//        }
//       List<Commodity>commodityList=commService.findByIds(ids);
//        ExcelUtils<Commodity> utils = new ExcelUtils<>();
//        String path = "d:\\Commodity"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".xls";
//        try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path))){
//            utils.export(commodityList,bos);
//        }catch (Exception e){
//            out.print(String.format(ALERT_BACK,"导出失败"));
//            e.printStackTrace();
//        }
//        out.print(String.format(ALERT_BACK,"导出成功"));
        List<Commodity>commodityList=commService.findByIds(ids);
        for (Commodity commodity : commodityList) {
            System.out.println(commodity);
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("获取excel测试表格");
        HSSFRow row = null;
        row = sheet.createRow(0);//创建第一个单元格
        row.setHeight((short) (26.25 * 20));
        row.createCell(0).setCellValue("库存信息列表");//为第一行单元格设值

        /*为标题设计空间
         * firstRow从第1行开始
         * lastRow从第0行结束
         *从第1个单元格开始
         * 从第3个单元格结束
         */
        CellRangeAddress rowRegion = new CellRangeAddress(0, 0, 0, 2);
        sheet.addMergedRegion(rowRegion);

      /*CellRangeAddress columnRegion = new CellRangeAddress(1,4,0,0);
      sheet.addMergedRegion(columnRegion);*/

        row = sheet.createRow(1);
        row.setHeight((short) (22.50 * 20));//设置行高
        row.createCell(0).setCellValue("序号");//为第一个单元格设值
        row.createCell(1).setCellValue("商品编码");//为第二个单元格设值
        row.createCell(2).setCellValue("商品条形码");//为第三个单元格设值
        row.createCell(3).setCellValue("商品名称");//为第四个单元格设值
        row.createCell(4).setCellValue("品牌名称");
        row.createCell(5).setCellValue("生产地址");
        row.createCell(6).setCellValue("库存id");
        row.createCell(7).setCellValue("商品描述");
        //遍历所获取的数据
        for (int i = 0; i < commodityList.size(); i++) {
            row = sheet.createRow(i + 2);
            Commodity commodity= commodityList.get(i);
            row.createCell(0).setCellValue(commodity.getId());
            row.createCell(1).setCellValue(commodity.getCommCode());
            row.createCell(2).setCellValue(commodity.getCommBarCode());
            row.createCell(3).setCellValue(commodity.getCommName());
            row.createCell(5).setCellValue(commodity.getCommBrand().getBname());
            row.createCell(6).setCellValue(commodity.getAddress());
            row.createCell(7).setCellValue(commodity.getKunncunId());
            row.createCell(8).setCellValue(commodity.getDes());
        }

        sheet.setDefaultRowHeight((short) (16.5 * 20));
        //列宽自适应
        for (int i = 0; i <= 13; i++) {
            sheet.autoSizeColumn(i);
        }
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        OutputStream os = response.getOutputStream();
        response.setHeader("Content-disposition", "attachment;filename=KuCun"+new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())+".xls");//默认Excel名称
        wb.write(os);
        os.flush();
        os.close();
    }



    @RequestMapping("/showPage")
    public String showPage(@RequestParam(defaultValue = "1") Integer index, Commodity commodity, ModelMap map) {

        PageInfo<Commodity> pageInfo = commService.show(index, commodity);
        List<CommBrand> brandList = brandDao.findAll();
        map.addAttribute("brands", brandList);
        List<CommType> commTypes = typeDao.findAll();
        map.addAttribute("types", commTypes);
        map.addAttribute("info", pageInfo);
        map.addAttribute("commName", commodity.getCommName());
        map.addAttribute("brandId", commodity.getBrandId());
        map.addAttribute("commTypeId", commodity.getCommTypeId());
        map.addAttribute("status", commodity.getStatus());
        return "shangpin/show";
    }

    @Autowired
    private ChDao chDao;

    @Autowired
    private GoodsDao goodsDao;
    //这里是添加页面动态下拉框
    @RequestMapping("/addShow")
    public String addshow(ModelMap map) {
        List<CommBrand> brandList = brandDao.findAll();
        List<CommType> commTypes = typeDao.findAll();
        List<Channel> channelList = chDao.findAll();
        List<Goods> goodsList=goodsDao.findAll();
        map.addAttribute("goodsList",goodsList);
        map.addAttribute("brandList", brandList);
        map.addAttribute("commTypes", commTypes);
        map.addAttribute("channelList", channelList);

        return "shangpin/add";
    }

    //这里是添加
    @RequestMapping("/shangpin_add")
    public void add(Commodity commodity, HttpServletResponse response, int[] ch) {
        response.setContentType("text/html;charset=utf-8");
        System.out.println(commodity);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Integer i = commService.add(commodity, ch);
        if (i > 0) {
            writer.print("<script>alert('添加成功');location.href='showPage';</script>");
        } else {
            writer.print("<script>alert('添加失败');location.href='showPage';</script>");
        }
    }

    //这里是商品修改页面的回显
    @RequestMapping("/shangpin_showBack")
    public String showBack(Integer commId, ModelMap map) {
        Commodity commodity = commService.findByCommId(commId);
        map.addAttribute("comm", commodity);
        List<CommBrand> brandList = brandDao.findAll();
        List<CommType> commTypes = typeDao.findAll();
        List<Channel> channelList = chDao.findAll();
        List<Goods> goodsList=goodsDao.findAll();
        map.addAttribute("goodsList",goodsList);
        map.addAttribute("brandList", brandList);
        map.addAttribute("commTypes", commTypes);
        map.addAttribute("channelList", channelList);
        if (commodity.getCstatus()==0){
            return "shangpin/update";
        }else{
            return "shangpin/chuxiaoupdate";
        }

    }


    @RequestMapping("/shangpin_update")
    public void update(Commodity commodity, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Integer i = commService.update(commodity);
        System.out.println("==============="+commodity.getCstatus());
        if (i > 0) {
            if (commodity != null) {
                if (commodity.getCstatus() == 0) {
                    writer.print("<script>alert('修改成功');location.href='showPage';</script>");
                } else if (commodity.getCstatus()==1){
                    writer.print("<script>alert('修改成功');location.href='chuxiaoShow';</script>");
                }
            } else {
                writer.print("<script>alert('暂无促销商品跳转到商品页面');location.href='showPage';</script>");
            }
        } else {
            if (commodity!=null){
                if (commodity.getCstatus() == 0) {
                    writer.print("<script>alert('修改失败');location.href='showPage';</script>");
                } else if (commodity.getCstatus()==1){
                    writer.print("<script>alert('修改失败');location.href='chuxiaoShow';</script>");
                }
            }else {
                writer.print("<script>alert('修改失败');location.href='showPage';</script>");
            }
        }
    }

    @Autowired
    private ChService chService;

    //删除渠道表
    @RequestMapping("deleteCh")
    public void delCh(Integer chid, HttpServletResponse response, Integer commId) {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Integer i = chService.del(chid,commId);
        if (i > 0) {
            writer.print("<script>alert('删除成功');location.href='shangpin_showBack?commId=" + commId + "';</script>");
        } else {
            writer.print("<script>alert('删除失败');location.href='shangpin_showBack?commId=" + commId + "';</script>");
        }
    }


    @RequestMapping("/addCh.ftl")
    public String addC(Integer commId, double cbPrice, ModelMap map) {
        map.addAttribute("commId", commId);
        map.addAttribute("cbPrice", cbPrice);

        return "shangpin/addCh";
    }

    //渠道的新增
    @RequestMapping("/addCh")
    public void addCh(Integer commId, double cbPrice, String cname, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Integer i = commService.addCh(commId, cbPrice, cname);
        if (i > 0) {
            writer.print("<script>alert('添加成功');location.href='shangpin_showBack?commId=" + commId + "';</script>");
        } else {
            writer.print("<script>alert('添加失败');location.href='shangpin_showBack?commId=" + commId + "';</script>");
        }

    }


    @RequestMapping("/chuxiaoShow")
    public String chuxiaoShow(@RequestParam(defaultValue = "1") Integer index, String commName, Integer brandId, Integer commTypeId, Integer status, ModelMap map) {
        List<CommBrand> brandList = brandDao.findAll();
        List<CommType> commTypes = typeDao.findAll();
        List<Channel> channelList = chDao.findAll();
        map.addAttribute("brands", brandList);
        map.addAttribute("types", commTypes);
        map.addAttribute("channelList", channelList);
        map.addAttribute("commName", commName);
        map.addAttribute("brandId", brandId);
        map.addAttribute("commTypeId", commTypeId);
        map.addAttribute("status", status);
        PageInfo<Commodity> info = commService.chuxiaoShow(index, commName, brandId, commTypeId, status);
        map.addAttribute("info", info);
        return "shangpin/chuxiaoShow";
    }

    @RequestMapping("/chuxiaoAdd")
    public String chuxiaoAdd(ModelMap map){
        List<CommBrand> brandList = brandDao.findAll();
        List<CommType> commTypes = typeDao.findAll();
        List<Channel> channelList = chDao.findAll();
        List<Goods> goodsList=goodsDao.findAll();
        map.addAttribute("goodsList",goodsList);
        map.addAttribute("brandList", brandList);
        map.addAttribute("commTypes", commTypes);
        map.addAttribute("channelList", channelList);
        return "shangpin/chuxiaoAdd";
    }

    //导出表格
    @RequestMapping("/daochuShangpin")
    public void daochuExcel(int[] commIds){
        for (int commId : commIds) {
            System.out.println(commId);
        }

    }
}
